package com.example.webdome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.webdome.enums.ValidationEnums;
import com.example.webdome.mapper.UserMapper;
import com.example.webdome.mapper.ValidationMapper;
import com.example.webdome.pojo.LoginRequest;
import com.example.webdome.pojo.Result;
import com.example.webdome.pojo.User;
import com.example.webdome.pojo.Validation;
import com.example.webdome.service.UserService;
import com.example.webdome.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private ValidationMapper validationMapper;

    @Resource
    private userIdUtils userIdUtils;

    @Resource
    private spiltUtils spiltUtils;
    @Resource
    private decryptToken decryptToken;
    @Resource
    private OnlineUserStatsService onlineUserStatsService;

    @Override
    public Result login(LoginRequest loginRequest, HttpServletResponse response) {
        //判断用户名密码是否为空
        if (StringUtils.isEmpty(loginRequest.getEmail()) || StringUtils.isEmpty(loginRequest.getPassword())) {
            return Result.ACCOUNT();
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", loginRequest.getEmail());

        //查询是否有此用户
        User login = userMapper.selectOne(queryWrapper);
        if (login == null) {
            return Result.failed();
        }
        //判断密码是否正确
        if (!login.getPassword().equals(loginRequest.getPassword())) {
            return Result.failed();
        }
        //将username加密（HS256）放入token中用来鉴权
        String Token = JwtUtil.createToken(loginRequest.getPassword() + ":" + loginRequest.getEmail());
        // 将 Token 存入 Cookie 中
        if (Token != null) {
            Cookie cookie = new Cookie("token", Token);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            onlineUserStatsService.online(login.getId());
            return Result.success("登录成功！");
        }
        return Result.failed("登陆失败！");
    }

    @Override
    public Result findPassWord(String email, User user, String code) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> e = queryWrapper.eq("email", email);
        if (e != null) {
            Date date = new Date();
            //查询验证码
            QueryWrapper<Validation> validationWrapper = new QueryWrapper<>();
            validationWrapper.eq("code", code);
            validationWrapper.ge("time", date);
            validationWrapper.eq("type", ValidationEnums.FIND_PASSWORD.getType());
            Validation existCode = validationMapper.selectOne(validationWrapper);
            if (existCode != null) {
                int i = userMapper.updateById(user);
                if (i > 0) {
                    return Result.success("修改成功！");
                }
                return Result.failed("修改失败！");
            }
            return Result.failed("验证码错误或者失效！");
        }
        return Result.failed("没有此用户！");
    }

    @Override
    public Result tokenCount() {
        Long count = this.onlineUserStatsService.count();
        return Result.success("当前登录的用户为：" + count);
    }

    @Override
    public Result outLogin(String token, HttpServletResponse response) {
        String pe = decryptToken.decrypt(token);
        if (pe != null) {
            String email = spiltUtils.getEmail(pe);
            Integer userId = userIdUtils.getUserId(email);
            Cookie cookie = new Cookie("token", null);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            onlineUserStatsService.outOnline(userId);
            return Result.success("退出登录成功！");
        }
        return Result.failed("您还没有登录！");
    }


    @Override
    public Result register(User user, String code) {
        Date date = new Date();
        //查询验证码
        QueryWrapper<Validation> validationWrapper = new QueryWrapper<>();
        validationWrapper.eq("code", code);
        validationWrapper.ge("time", date);
        validationWrapper.eq("type", ValidationEnums.REGISTER.getType());
        Validation existCode = validationMapper.selectOne(validationWrapper);
        if (existCode != null) {
            String email = user.getEmail();
            String password = user.getPassword();
            //注册用户信息
            if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
                return Result.ACCOUNT();
            }


            //查询是否存在同名的用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", user.getEmail());
            User existUser = userMapper.selectOne(queryWrapper);

            if (existUser != null) {
                return Result.PARAMS();
            }
            int insertResult = userMapper.insert(user);
            if (insertResult <= 0) {
                return Result.failed("注册失败！");
            }
            return Result.success("注册成功！");
        }
        return Result.failed("验证码错误！或者过期！请重新获取");

    }

    @Override
    public User getByEmail(String email) {
        return lambdaQuery().eq(User::getEmail, email).one();
    }
}
